﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BoAddonBiz_FreightForwarder.BusinessBase;
using System.Xml;
using System.Text.RegularExpressions;

namespace BoAddonBiz_FreightForwarder.Cost.OpenInvoice
{
    /// <summary>
    /// 电子发票
    /// </summary>
    /// <author>WangPeng</author>
    [ControlB1FormAttribute(IsNew = true, FormType = B1FormTypes.ado_AVA_Invoice)]
    class B1Form_Invoice : SAPBoAddon.B1Form
    {
        #region protected override
        protected override bool BeforeSaveCheckFormData()
        {
            string CardName = string.Empty, Invoice = string.Empty, InvoiceTaxType = string.Empty, TaxArea = string.Empty;
            decimal InvoiceAmount = 0, Amount = 0;

            CardName = CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV").GetValue("U_CardName", 0).Trim();
            Invoice = CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV").GetValue("U_Invoice", 0).Trim();
            InvoiceTaxType = CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV").GetValue("U_InvoiceTaxType", 0).Trim();
            InvoiceAmount = Convert.ToDecimal(CurrentForm.DataSources.UserDataSources.Item("InvAmount").Value.ToString());
            Amount = Convert.ToDecimal(CurrentForm.DataSources.UserDataSources.Item("Amount").Value.Trim());
            TaxArea = CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV").GetValue("U_TaxArea", 0).Trim();
            if (string.IsNullOrWhiteSpace(CardName))
            {
                SBOApp.MessageBox("客户不能为空");
                return false;
            }
            if (string.IsNullOrWhiteSpace(Invoice))
            {
                SBOApp.MessageBox("发票抬头不能为空");
                return false;
            }
            if (string.IsNullOrWhiteSpace(InvoiceTaxType))
            {
                SBOApp.MessageBox("发票类型不能为空");
                return false;
            }
            if (InvoiceAmount <= 0)
            {
                SBOApp.MessageBox("发票金额不为空，请检查发票明细！");
                return false;
            }
            if (Amount <= 0)
            {
                SBOApp.MessageBox("对账单金额不能为空，请检查对账单的数据！");
                return false;
            }
            if (string.IsNullOrWhiteSpace(TaxArea))
            {
                SBOApp.MessageBox("开票地区 不能为空");
                return false;
            }
            SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_INV1");
            for (int i = 0; i < dbds.Size; i++)
            {
                if (string.IsNullOrEmpty(dbds.GetValue("U_CargoName", i).Trim()))
                {
                    SBOApp.MessageBox("发票明细没有选择，请检查发票明细！");
                    return false;
                }
            }

            dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_INV2");
            for (int i = 0; i < dbds.Size; i++)
            {
                if (string.IsNullOrEmpty(dbds.GetValue("U_BaseEntry", i).Trim()))
                {
                    SBOApp.MessageBox("没有添加对账单，请检查对账单！");
                    return false;
                }
            }
            CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV").SetValue("Object", 0, "AVA_Invoice");
            if (string.IsNullOrEmpty(CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV").GetValue("Object", 0).Trim()))
            {
                SBOApp.MessageBox("保存单据出现问题，请窗体此单据，重新录入");
                return false;
            }
            CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV").SetValue("U_Amount", 0, CurrentForm.DataSources.UserDataSources.Item("InvAmount").Value);
            return true;
        }

        protected override void FormEditModeChange(SAPBoAddon.frmItemEditMode frmEditMode)
        {
            if (frmEditMode == SAPBoAddon.frmItemEditMode.fe_AddMode)
            {
                SAPbouiCOM.DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV");
                dbds.SetValue("U_ApplyDate", dbds.Offset, DateTime.Now.ToString("yyyyMMdd"));
                SAPBoAddon.B1Assistant.Item.SetValue(CurrentForm, "Apply", SBOCompany.UserSignature.ToString(), SAPbouiCOM.BoSearchKey.psk_ByValue);
                CurrentForm.DataSources.UserDataSources.Item("DocAmount").Value = "";
                CurrentForm.DataSources.UserDataSources.Item("DocTAmount").Value = "";
                CurrentForm.DataSources.UserDataSources.Item("InvAmount").Value = "";
                CurrentForm.DataSources.UserDataSources.Item("Amount").Value = "";
                CurrentForm.DataSources.UserDataSources.Item("Currency").Value = "";
                CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV").SetValue("U_Rate", 0, "");
                //CurrentForm.DataSources.UserDataSources.Item("Rate").Value = "";
            }
        }

        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            this.FormSetting.FormType = B1FormTypes.ado_AVA_Invoice;
            this.FormSetting.FormFileName = FormSetting.FormType + "Form.srf";
            #region item control
            string[] DisableItms = { "3", "7", "InvDate", "InvAmount", "InvNum", "Invoice", "49", "42", "43", "l43", "50", "51", "52", "53", "57", "58", "58" };
            #region Add
            FormSetting.FormModeSetting.itmNewModeEnable = Utils.GetFormItems(FormSetting.FormXmlDocument, true, DisableItms);
            FormSetting.FormModeSetting.itmNewModeDisable = DisableItms;
            #endregion
            #region operation
            FormSetting.FormModeSetting.StatusItemUID = "7";
            SAPBoAddon.BrowseModeSetting BrowseModeSetting;
            #region 正操作-P
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "P";
            string[] DisableItms_StatusP = DisableItms;
            if (Utils.GetDemptmentCode() == 1) //财务code=1;manager code=13
            {
                List<string> List_temp = new List<string>(DisableItms_StatusP);
                List_temp.Remove("InvNum");
                DisableItms_StatusP = List_temp.ToArray();
            }
            BrowseModeSetting.itmBrowseModeEnable = Utils.GetFormItems(FormSetting.FormXmlDocument, true, DisableItms_StatusP);
            BrowseModeSetting.itmBrowseModeDisable = DisableItms_StatusP;

            #endregion
            #region 开票中-O
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "O";
            BrowseModeSetting.itmBrowseModeDisable = Utils.GetFormItems(FormSetting.FormXmlDocument, true, new string[] { "2" });
            #endregion
            #region 已获取-G
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "G";
            BrowseModeSetting.itmBrowseModeDisable = Utils.GetFormItems(FormSetting.FormXmlDocument, true, new string[] { "2" });
            #endregion
            #region 已开票-C
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "C";
            BrowseModeSetting.itmBrowseModeDisable = Utils.GetFormItems(FormSetting.FormXmlDocument, true, new string[] { "2" });
            #endregion
            #region 已冲销-R
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "R";
            BrowseModeSetting.itmBrowseModeDisable = Utils.GetFormItems(FormSetting.FormXmlDocument, true, new string[] { "2" });
            #endregion
            #region 已作废-D
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "D";
            BrowseModeSetting.itmBrowseModeDisable = Utils.GetFormItems(FormSetting.FormXmlDocument, true, new string[] { "2" });
            #endregion
            #endregion
            #region find
            FormSetting.FormModeSetting.itmFindModeEnable = Utils.GetFormItems(FormSetting.FormXmlDocument); ;//查找状态可编辑的控件
            #endregion
            #endregion

            FormSetting.AutoGetObjectNextNumber = true;

            FormSetting.MatrixSetting.MtxUID = "mtx_0";
            FormSetting.MatrixSetting.MenuAddNewLine = false;
            FormSetting.MatrixSetting.AutoAddNewLine = false;
            FormSetting.MatrixSetting.NotAllowNoLineSave = false;
            FormSetting.MatrixSetting.AutoLineKeyCol = "col_0";
            FormSetting.MatrixSetting.BeforeSaveFixDbDataSourceData = true;
            FormSetting.MatrixSetting.BeforeSaveDeleteNoValueLine = true;
            FormSetting.MatrixSetting.TableKeyField = "LineId";
            FormSetting.MatrixSetting.TableVisOrder = "VisOrder";
            FormSetting.MatrixSetting.PrimaryLineCol = "col_f";
            FormSetting.MatrixSetting.TableName = "@AVA_INV1";
            FormSetting.MatrixSetting.Add();
        }

        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {
            Utils.InitialItemComboBox(SBOCompany, this.CurrentForm.Items.Item("InvCurr"), "CurrCode", "CurrName", "OCRN", null, "RMB");//费用币种
            Utils.LoadUser(this.CurrentForm, this.SBOCompany, "Apply");
            if (!String.IsNullOrEmpty(InitPar.FatherFormUID) && new Regex(@"\b\d+\b").Match(InitPar.FatherFormUID).Success)
            {
                this.CurrentForm.Mode = SAPbouiCOM.BoFormMode.fm_FIND_MODE;
                SAPBoAddon.B1Assistant.Item.SetValue(this.CurrentForm, this.CurrentForm.DataBrowser.BrowseBy, InitPar.FatherFormUID);
                this.CurrentForm.Items.Item("1").Click(SAPbouiCOM.BoCellClickType.ct_Regular);
            }
            SumAmount(CurrentForm);
        }
        #endregion
        #region contructor
        public B1Form_Invoice()
        {
            this.frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(B1Form_Invoice_frm_ItemEvent);
            this.frm_ChooseFormListEvent += new SAPBoAddon.IB1FormEvents.B1ChooseFormListEventEventHandler(B1Form_Invoice_frm_ChooseFormListEvent);
            this.frm_MenuEvent += new SAPBoAddon.IB1FormEvents.B1MenuEventEventHandler(B1Form_Invoice_frm_MenuEvent);
            this.frm_RightClickEvent += new SAPBoAddon.IB1FormEvents.B1RightClickEventEventHandler(B1Form_Invoice_frm_RightClickEvent);
            this.frm_FormDataEvent += new SAPBoAddon.IB1FormEvents.B1FormDataEventEventHandler(B1Form_Invoice_frm_FormDataEvent);
        }

        #endregion
        #region events
        void B1Form_Invoice_frm_ChooseFormListEvent(SAPBoAddon.B1AddonBase.B1ChooseFormList pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {
                #region 过滤条件
                SAPbouiCOM.ChooseFromList cfl = this.CurrentForm.ChooseFromLists.Item(pVal.ChooseFromListUID);
                SAPbouiCOM.Conditions cons;
                SAPbouiCOM.Condition con;
                switch (pVal.ChooseFromListUID)
                {
                    case "CFL_BP":
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup14";//结算单位
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = SAPbouiCOM.BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "CardType";
                        con.CondVal = "C";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = SAPbouiCOM.BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                };
                #endregion
            }
            else
            {
                #region 结果
                if (pVal.Action_Success)
                {
                    switch (pVal.ChooseFromListUID)
                    {
                        case "CFL_BP":
                            SAPbouiCOM.DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV");
                            dbds.SetValue("U_CardCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                            dbds.SetValue("U_CardName", dbds.Offset, pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                            #region 获取发票信息
                            GetInvoice(pVal.SelectedObjects.GetValue("CardCode", 0).ToString().Trim(), "1");
                            #endregion
                            #region 获取销货单位信息
                            GetDeliver("1");
                            #endregion
                            break;
                        case "CFL_InvoiceItem":
                            #region 获取发票明细
                            SAPbouiCOM.DBDataSource dbds1 = this.CurrentForm.DataSources.DBDataSources.Item("@AVA_INV1");
                            SAPbouiCOM.Matrix omtx = (SAPbouiCOM.Matrix)this.CurrentForm.Items.Item("mtx_0").Specific;
                            int CurrentRow = pVal.Row;
                            omtx.GetLineData(CurrentRow);
                            for (int i = 0; i < pVal.SelectedObjects.Rows.Count; i++)
                            {
                                dbds1.Offset = SAPBoAddon.B1Assistant.Matrix.GetdbDsOffset(omtx, CurrentRow, "col_f", dbds1);
                                dbds1.SetValue("U_CargoCode", dbds1.Offset, pVal.SelectedObjects.GetValue("U_CargoCode", i).ToString().Trim());
                                dbds1.SetValue("U_CargoName", dbds1.Offset, pVal.SelectedObjects.GetValue("U_CargoName", i).ToString());
                                dbds1.SetValue("U_ShortName", dbds1.Offset, pVal.SelectedObjects.GetValue("U_ShortName", i).ToString());
                                dbds1.SetValue("U_Stlye", dbds1.Offset, pVal.SelectedObjects.GetValue("U_Stlye", i).ToString());
                                dbds1.SetValue("U_Unit", dbds1.Offset, pVal.SelectedObjects.GetValue("U_Unit", i).ToString());
                                dbds1.SetValue("U_Quantity", dbds1.Offset, pVal.SelectedObjects.GetValue("U_Quantity", i).ToString());
                                dbds1.SetValue("U_Price", dbds1.Offset, pVal.SelectedObjects.GetValue("U_Price", i).ToString());
                                dbds1.SetValue("U_Amount", dbds1.Offset, pVal.SelectedObjects.GetValue("U_Amount", i).ToString());
                                dbds1.SetValue("U_Rate", dbds1.Offset, pVal.SelectedObjects.GetValue("U_Rate", i).ToString());
                                dbds1.SetValue("U_TaxAmount", dbds1.Offset, pVal.SelectedObjects.GetValue("U_TaxAmount", i).ToString());
                                dbds1.SetValue("U_IsTax", dbds1.Offset, "Y");
                                omtx.SetLineData(CurrentRow);
                                SAPBoAddon.B1Assistant.Matrix.AutoAddNewLine(this.CurrentForm, "mtx_0", "col_f", "@AVA_INV1", CurrentRow, "Lineid", "Lineid", true);
                                CurrentRow += 1;
                            }
                            #endregion
                            break;
                    }
                }
                #endregion
            }
        }
        void B1Form_Invoice_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.Before_Action)
            { }
            else
            {
                #region panel
                if (pVal.ItemUID == "tab_0" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    CurrentForm.PaneLevel = 1;
                }
                if (pVal.ItemUID == "tab_1" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    CurrentForm.PaneLevel = 2;
                }
                #endregion
                #region Choose Button
                //发票信息
                if (pVal.ItemUID == "btnInv" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV");
                    string CardCode = dbds.GetValue("U_CardCode", dbds.Offset).Trim();
                    GetInvoice(CardCode, "n");
                }
                //销货单位
                if (pVal.ItemUID == "btnDel" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    GetDeliver("n");
                }
                #endregion
                #region add & del line
                if (pVal.ItemUID == "Add" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    SAPBoAddon.B1Assistant.Matrix.AutoAddNewLine(CurrentForm, "mtx_0", "col_f", "@AVA_INV1", -1);
                }
                if (pVal.ItemUID == "Del" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    if (CurrentForm.PaneLevel == 1)
                        SAPBoAddon.B1Assistant.Matrix.DeleteSelectedRow(CurrentForm.UniqueID, "mtx_0");
                    else
                        SAPBoAddon.B1Assistant.Matrix.DeleteSelectedRow(CurrentForm.UniqueID, "mtx_1");
                    SumAmount(CurrentForm);
                }
                #endregion
                #region item change
                if (pVal.ItemUID == "mtx_0" && pVal.ColUID == "col_4" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_VALIDATE)
                {
                    CalculationAmount(pVal.Row);
                    SumAmount(CurrentForm);
                }
                #endregion
                #region 添加对账单
                if (pVal.ItemUID == "btnConf" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    AddConfrimBill();
                }
                #endregion
                #region 发送开票信息
                if (pVal.ItemUID == "btnSend" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    CreateInvoiceXml();
                }
                #endregion
                #region 黄键头
                //if (pVal.ItemUID == "mtx_1" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_MATRIX_LINK_PRESSED)
                //{
                //    SBOApp.Menus.Item("2061").Activate();
                //    string DraftEntry = SAPBoAddon.B1Assistant.Matrix.GetCellValue(CurrentForm.Items.Item("mtx_1").Specific, "col_1", pVal.Row);
                //    SAPbouiCOM.Form ChooseDraft = SBOApp.Forms.GetFormByTypeAndCount(3001, 1);
                //    //ChooseDraft.Visible = true;
                //    SAPBoAddon.B1Assistant.Item.SetValue(ChooseDraft, "8", "0", SAPbouiCOM.BoSearchKey.psk_ByValue);
                //    SAPBoAddon.B1Assistant.Item.SetValue(ChooseDraft, "16", "Y");
                //    SAPBoAddon.B1Assistant.Item.SetValue(ChooseDraft, "18", "N");
                //    SAPBoAddon.B1Assistant.Item.SetValue(ChooseDraft, "5", "Y");
                //    SAPBoAddon.B1Assistant.Item.SetValue(ChooseDraft, "6", "Y");
                //    ChooseDraft.Items.Item("1").Click(SAPbouiCOM.BoCellClickType.ct_Regular);
                //    SAPbouiCOM.Form DraftList = SBOApp.Forms.GetFormByTypeAndCount(3002, 1);
                //    SAPbouiCOM.Matrix omtx = DraftList.Items.Item("3").Specific;
                //    omtx.SetCellFocus(2,1);
                //    DraftList.Items.Item("3").Click(SAPbouiCOM.BoCellClickType.ct_Right);                   
                //}
                #endregion
            }
        }
        void B1Form_Invoice_frm_RightClickEvent(SAPBoAddon.B1AddonBase.B1ContextMenuInfo eventInfo, ref bool BubbleEvent)
        {
            if (eventInfo.BeforeAction)
            {
                if (eventInfo.EventType == SAPbouiCOM.BoEventTypes.et_RIGHT_CLICK)
                {
                    //添加菜单
                    AddRightClickMenus();
                }
            }
        }
        void B1Form_Invoice_frm_MenuEvent(SAPBoAddon.B1AddonBase.B1MenuEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {
                if (pVal.MenuUID == "Canceled")
                {
                    Canceled();
                }
                if (pVal.MenuUID == "Invalid")
                {
                    Invalid();
                }
            }
            else
            {
                //移除菜单
                RemoveRightClickMenus();
            }
        }
        void B1Form_Invoice_frm_FormDataEvent(SAPBoAddon.B1AddonBase.B1BusinessObjectInfo pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction == false)
            {
                if ((pVal.EventType == SAPbouiCOM.BoEventTypes.et_FORM_DATA_ADD || pVal.EventType == SAPbouiCOM.BoEventTypes.et_FORM_DATA_UPDATE) && pVal.ActionSuccess)
                {
                    UpdateInvoiceDraft();
                }
                if (pVal.EventType == SAPbouiCOM.BoEventTypes.et_FORM_DATA_LOAD && pVal.ActionSuccess)
                    SumAmount(CurrentForm);
            }
        }
        #endregion
        #region methods
        /// <summary>
        /// 获取发票信息
        /// </summary>
        /// <param name="CardCode"></param>
        /// <param name="n"></param>
        private void GetInvoice(string CardCode, string n)
        {
            SAPbobsCOM.Recordset rs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV");

            string SQL = @"select Address Name,Street Invoice,Block TaxNo,City AdrPho,ZipCode Bank,County CardNo
                                            From CRD1 
                                            Where AdresType = 'B' And CardCode = '" + CardCode + "' ";
            rs.DoQuery(SQL);
            if (rs.RecordCount > 0)
            {
                if (n == "1")
                {
                    if (rs.RecordCount == 1)
                    {
                        //获取开票信息
                        dbds.SetValue("U_Invoice", dbds.Offset, rs.Fields.Item("Invoice").Value);//发票抬头
                        dbds.SetValue("U_TaxpayerNo", dbds.Offset, rs.Fields.Item("TaxNo").Value);//纳税人识别号
                        dbds.SetValue("U_TaxpayerAddress", dbds.Offset, rs.Fields.Item("AdrPho").Value);//地址及电话
                        dbds.SetValue("U_TaxpayerBank", dbds.Offset, rs.Fields.Item("Bank").Value);//开户行
                        dbds.SetValue("U_TaxpayerCardNo", dbds.Offset, rs.Fields.Item("CardNo").Value);//账号
                    }
                    else
                        return;
                }
                else
                {
                    #region 选择发票信息
                    SAPBoAddon.B1FormList.B1FormListSetting oFormListSetting = new SAPBoAddon.B1FormList.B1FormListSetting("Invoice", SAPBoAddon.B1FormList.FL_FillValueType.AddonEdit);
                    oFormListSetting.FormTitle = "发票信息";

                    oFormListSetting.ListSQL = String.Format(@"select Address Name,Street Invoice,Block TaxNo,City AdrPho,ZipCode Bank,County CardNo
                                            From CRD1 
                                            Where AdresType = 'B' And CardCode = '{0}'", CardCode);

                    oFormListSetting.FormType = CurrentForm.TypeEx;
                    oFormListSetting.FormUID = CurrentForm.UniqueID;
                    oFormListSetting.ItemUID = "btnInv";
                    oFormListSetting.FillSelectedField = "btnInv";
                    oFormListSetting.SelectionMode = SAPbouiCOM.BoMatrixSelect.ms_Single;

                    oFormListSetting.FindField = "Name";

                    oFormListSetting.MtxColumns.Add();
                    oFormListSetting.MtxColumns.Enabled = false;
                    oFormListSetting.MtxColumns.Title = "发票信息名称";
                    oFormListSetting.MtxColumns.Add();
                    oFormListSetting.MtxColumns.Enabled = false;
                    oFormListSetting.MtxColumns.Title = "抬头";
                    oFormListSetting.MtxColumns.Add();
                    oFormListSetting.MtxColumns.Enabled = false;
                    oFormListSetting.MtxColumns.Title = "纳税人识别号";
                    oFormListSetting.MtxColumns.Add();
                    oFormListSetting.MtxColumns.Enabled = false;
                    oFormListSetting.MtxColumns.Title = "地址及电话";
                    oFormListSetting.MtxColumns.Add();
                    oFormListSetting.MtxColumns.Enabled = false;
                    oFormListSetting.MtxColumns.Title = "开户行";
                    oFormListSetting.MtxColumns.Add();
                    oFormListSetting.MtxColumns.Enabled = false;
                    oFormListSetting.MtxColumns.Title = "账号";
                    oFormListSetting.MtxColumns.Add();

                    SAPBoAddon.B1Addon.B1Addon.B1FormList.Form_CreateListForm(oFormListSetting);
                    SAPBoAddon.B1Addon.B1Addon.B1FormList.B1ListFormEvent += new SAPBoAddon.B1FormList.B1FormList.B1ListFormEventEventHandler(B1FormList_B1ListFormEvent_Invoice);
                    #endregion
                }
            }
        }
        void B1FormList_B1ListFormEvent_Invoice(SAPBoAddon.B1FormList.B1FormListEvents pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeEvent == false)
            {
                pVal.CloseForm = false;
                SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV");
                dbds.SetValue("U_Invoice", dbds.Offset, pVal.SelectedDataTable.GetValue("Invoice", 0));//发票抬头
                dbds.SetValue("U_TaxpayerNo", dbds.Offset, pVal.SelectedDataTable.GetValue("TaxNo", 0));//纳税人识别号
                dbds.SetValue("U_TaxpayerAddress", dbds.Offset, pVal.SelectedDataTable.GetValue("AdrPho", 0));//地址及电话
                dbds.SetValue("U_TaxpayerBank", dbds.Offset, pVal.SelectedDataTable.GetValue("Bank", 0));//开户行及账号                
                dbds.SetValue("U_TaxpayerCardNo", dbds.Offset, pVal.SelectedDataTable.GetValue("CardNo", 0));//开户行及账号                
                SAPBoAddon.B1Addon.B1Addon.B1FormList.B1ListFormEvent -= B1FormList_B1ListFormEvent_Invoice;
                if (CurrentForm.Mode != SAPbouiCOM.BoFormMode.fm_ADD_MODE && CurrentForm.Mode != SAPbouiCOM.BoFormMode.fm_UPDATE_MODE) CurrentForm.Mode = SAPbouiCOM.BoFormMode.fm_UPDATE_MODE;
            }
        }
        /// <summary>
        /// 获取销货单位
        /// </summary>
        /// <param name="n"></param>
        private void GetDeliver(string n)
        {
            SAPbobsCOM.Recordset rs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV");
            rs.DoQuery(@"SELECT U_Company,U_TaxNo,U_Bank+  U_CardNo BankNo,U_Address + U_Phone AdrPhe,U_Remarks FROM [@AVA_OCPY]");
            if (rs.RecordCount > 0)
            {
                if (n == "1")
                {
                    if (rs.RecordCount == 1)
                    {
                        dbds.SetValue("U_Deliver", dbds.Offset, rs.Fields.Item("U_Company").Value);//发票抬头
                        dbds.SetValue("U_DeliverTaxNo", dbds.Offset, rs.Fields.Item("U_TaxNo").Value);//纳税人识别号
                        dbds.SetValue("U_DeliverAddress", dbds.Offset, rs.Fields.Item("AdrPhe").Value);//地址及电话
                        dbds.SetValue("U_DeliverBank", dbds.Offset, rs.Fields.Item("BankNo").Value);//开户行及账号
                    }
                    else
                        return;

                }
                else
                {
                    #region 选择销货单位
                    SAPBoAddon.B1FormList.B1FormListSetting oFormListSetting = new SAPBoAddon.B1FormList.B1FormListSetting("Deliver", SAPBoAddon.B1FormList.FL_FillValueType.AddonEdit);
                    oFormListSetting.FormTitle = "销货单位";

                    oFormListSetting.ListSQL = String.Format(@"SELECT U_Company,U_TaxNo,U_Bank + U_CardNo BankNo,U_Address + U_Phone AdrPhe,U_Remarks FROM [@AVA_OCPY]");

                    oFormListSetting.FormType = CurrentForm.TypeEx;
                    oFormListSetting.FormUID = CurrentForm.UniqueID;
                    oFormListSetting.ItemUID = "btnDel";
                    oFormListSetting.FillSelectedField = "btnDel";
                    oFormListSetting.SelectionMode = SAPbouiCOM.BoMatrixSelect.ms_Single;

                    oFormListSetting.FindField = "U_Company";

                    oFormListSetting.MtxColumns.Add();
                    oFormListSetting.MtxColumns.Enabled = false;
                    oFormListSetting.MtxColumns.Title = "名称";
                    oFormListSetting.MtxColumns.Add();
                    oFormListSetting.MtxColumns.Enabled = false;
                    oFormListSetting.MtxColumns.Title = "纳税人识别号";
                    oFormListSetting.MtxColumns.Add();
                    oFormListSetting.MtxColumns.Enabled = false;
                    oFormListSetting.MtxColumns.Title = "地址及电话";
                    oFormListSetting.MtxColumns.Add();
                    oFormListSetting.MtxColumns.Enabled = false;
                    oFormListSetting.MtxColumns.Title = "开户行及账号";
                    oFormListSetting.MtxColumns.Add();
                    oFormListSetting.MtxColumns.Enabled = false;
                    oFormListSetting.MtxColumns.Title = "备注";
                    oFormListSetting.MtxColumns.Add();

                    SAPBoAddon.B1Addon.B1Addon.B1FormList.Form_CreateListForm(oFormListSetting);
                    SAPBoAddon.B1Addon.B1Addon.B1FormList.B1ListFormEvent += new SAPBoAddon.B1FormList.B1FormList.B1ListFormEventEventHandler(B1FormList_B1ListFormEvent_Deliver);
                    #endregion
                }
            }
        }
        void B1FormList_B1ListFormEvent_Deliver(SAPBoAddon.B1FormList.B1FormListEvents pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeEvent == false)
            {
                pVal.CloseForm = false;
                SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV");
                dbds.SetValue("U_Deliver", dbds.Offset, pVal.SelectedDataTable.GetValue("U_Company", 0));//发票抬头
                dbds.SetValue("U_DeliverTaxNo", dbds.Offset, pVal.SelectedDataTable.GetValue("U_TaxNo", 0));//纳税人识别号
                dbds.SetValue("U_DeliverAddress", dbds.Offset, pVal.SelectedDataTable.GetValue("AdrPhe", 0));//地址及电话
                dbds.SetValue("U_DeliverBank", dbds.Offset, pVal.SelectedDataTable.GetValue("BankNo", 0));//开户行及账号
                SAPBoAddon.B1Addon.B1Addon.B1FormList.B1ListFormEvent -= B1FormList_B1ListFormEvent_Deliver;
            }
        }
        /// <summary>
        /// 计算行总计及税额
        /// </summary>
        /// <param name="row"></param>
        private void CalculationAmount(int row)
        {
            decimal Price = 0;
            string IsTax = string.Empty;
            SAPbouiCOM.Matrix mtx = CurrentForm.Items.Item("mtx_0").Specific;
            SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_INV1");
            dbds.Offset = SAPBoAddon.B1Assistant.Matrix.GetdbDsOffset(mtx, row, "col_f", dbds);
            mtx.GetLineData(row);
            Price = Convert.ToDecimal(dbds.GetValue("U_Price", dbds.Offset).Trim());
            dbds.SetValue("U_Amount", dbds.Offset, Price.ToString());
            mtx.SetLineData(row);
        }
        /// <summary>
        /// 合计利润
        /// </summary>
        private void SumAmount(SAPbouiCOM.Form oForm)
        {
            decimal Amount = 0;
            decimal TaxAmount = 0;
            decimal ConfirmBillAmount = 0;
            string Currency = string.Empty;
            //decimal Rate = 0;
            string Status = SAPBoAddon.B1Assistant.Item.GetValue(oForm, "7").ToString().Trim();
            SAPbouiCOM.DBDataSource dbds1 = oForm.DataSources.DBDataSources.Item("@AVA_INV1");
            SAPbouiCOM.DBDataSource dbds2 = oForm.DataSources.DBDataSources.Item("@AVA_INV2");

            for (int i = 0; i < dbds1.Size; i++)
            {
                Amount += Convert.ToDecimal(dbds1.GetValue("U_Amount", i).Trim());
                TaxAmount += Convert.ToDecimal(dbds1.GetValue("U_TaxAmount", i).Trim());
            }
            for (int i = 0; i < dbds2.Size; i++)
            {
                if (dbds2.GetValue("U_Direction", i).Trim() == "I")
                    ConfirmBillAmount += Convert.ToDecimal(dbds2.GetValue("U_Amount", i).Trim());
                else
                    ConfirmBillAmount -= Convert.ToDecimal(dbds2.GetValue("U_Amount", i).Trim());
                Currency = dbds2.GetValue("U_Currency", i).Trim();
                //Rate = Rate = Utils.GetRateByCurrency(Currency);
            }
            oForm.DataSources.UserDataSources.Item("DocAmount").Value = Amount.ToString();
            oForm.DataSources.UserDataSources.Item("DocTAmount").Value = TaxAmount.ToString();
            if (Status == "C" || Status == "Q" || Status == "R")
                oForm.DataSources.UserDataSources.Item("InvAmount").Value = (Amount + TaxAmount).ToString();
            else
                oForm.DataSources.UserDataSources.Item("InvAmount").Value = Amount.ToString();
            oForm.DataSources.UserDataSources.Item("Amount").Value = ConfirmBillAmount.ToString();
            oForm.DataSources.UserDataSources.Item("Currency").Value = Currency;
            //oForm.DataSources.DBDataSources.Item("@AVA_OINV").SetValue("U_Rate", 0, Rate.ToString());
            //oForm.DataSources.UserDataSources.Item("Rate").Value = Rate.ToString();
        }
        /// <summary>
        /// 添加对账单 
        /// </summary>
        private void AddConfrimBill()
        {
            SAPbouiCOM.Form oChildForm;
            SAPbouiCOM.Form oParentForm;
            SAPbouiCOM.Grid oGrid;
            SAPbouiCOM.DataTable dt;
            oParentForm = CurrentForm;
            if (oParentForm.Mode != SAPbouiCOM.BoFormMode.fm_ADD_MODE && oParentForm.Mode != SAPbouiCOM.BoFormMode.fm_OK_MODE && oParentForm.Mode != SAPbouiCOM.BoFormMode.fm_UPDATE_MODE) return;
            oChildForm = SAPBoAddon.B1Assistant.Form.LoadToSBOApplciation(System.Windows.Forms.Application.StartupPath + @"\Form\AVA_InvoiceListForm.srf", "", true);
            #region 设置主了窗体UID
            oParentForm.DataSources.UserDataSources.Item("ChildUID").Value = oChildForm.UniqueID;
            oChildForm.DataSources.UserDataSources.Item("ParentUID").Value = oParentForm.UniqueID;
            #endregion
            oGrid = oChildForm.Items.Item("Grid").Specific;
            //oGrid.SelectionMode = SAPbouiCOM.BoMatrixSelect.ms_Single;
            dt = oChildForm.DataSources.DataTables.Add("Table");
            oChildForm.Title = oChildForm.Title + " - 对账单";
            dt.ExecuteQuery(@"
                           SELECT Case When T0.ObjType = '13' Then '应收' Else '应付' End Direction,T0.DocEntry,T0.CardName,T0.CreateDate,T0.DocCur,T0.DocRate
	                            ,T0.DocTotal,T1.Amount - ISNULL(T0.U_InvoiceAmount,0) Amount
                            FROM ODRF T0
	                            INNER JOIN (SELECT t0.DocEntry
						                            ,Case When T0.CurSource = 'L' Or T0.CurSource = 'S' 
							                            Then SUM(ISNULL(T1.LineTotal,0)) 
							                            ELSE 
								                            Case When T0.DocCur = 'RMB' Then  SUM(ISNULL(T1.Price * T1.Quantity,0))
									                            Else  SUM(ISNULL(T1.Price * T1.Quantity * case when T1.Rate = 0 then 1 else t1.rate end / T0.DocRate,0))
								                            End
						                            End Amount
				                            FROM ODRF T0
					                            INNER JOIN DRF1 T1 ON T0.DocEntry = T1.DocEntry
					                            INNER JOIN OITM T2 ON T1.ItemCode = T2.ItemCode
				                            Where T0.CANCELED = 'N' And T1.LinManClsd = 'N'
					                            And T2.ItmsGrpCod <> 100
				                            Group by T0.DocEntry,T0.CurSource,T0.DocCur,T0.DocRate
				                            ) T1 ON T0.DocEntry = T1.DocEntry
                            Where T0.CANCELED = 'N' And ISNULL(T0.U_IsInvoice,'N') = 'N' And ISNULL(T0.U_InvoiceAmount,0) <= 10
                                And T0.ObjType IN ('13','18')");
            oGrid.DataTable = dt;
            oChildForm.Items.Item("Grid").Enabled = false;
            SAPbouiCOM.ComboBox cmb = oChildForm.Items.Item("5").Specific;
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                cmb.ValidValues.Add(dt.Columns.Item(i).Name, oGrid.Columns.Item(i).TitleObject.Caption);
            }
            cmb.Select("DocEntry", SAPbouiCOM.BoSearchKey.psk_ByValue);
        }
        /// <summary>
        /// 创建发票信息
        /// </summary>
        private void CreateInvoiceXml()
        {
            if (CurrentForm.Mode != SAPbouiCOM.BoFormMode.fm_OK_MODE)
            {
                SBOApp.MessageBox("请保存单据，再发送！");
                return;
            }
            SAPbobsCOM.Recordset rs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            rs.DoQuery("SELECT Userid FROM OUSR Where Branch = '10' And UserID = " + SBOCompany.UserSignature);//用户只有在分属选择财务的才有权限
            if (rs.RecordCount <= 0)
            {
                SBOApp.MessageBox("您没有权限，只有财务人员才具有此权限！");
                return;
            }
            string DocEntry = CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV").GetValue("DocEntry", 0).Trim();
            rs.DoQuery(string.Format("UPDATE [@AVA_OINV] SET U_Status = 'O' Where DocEntry = '{0}'", DocEntry));
            this.CurrentForm.Mode = SAPbouiCOM.BoFormMode.fm_FIND_MODE;
            SAPBoAddon.B1Assistant.Item.SetEnabled(CurrentForm, this.CurrentForm.DataBrowser.BrowseBy, true);
            SAPBoAddon.B1Assistant.Item.SetValue(this.CurrentForm, this.CurrentForm.DataBrowser.BrowseBy, DocEntry);
            this.CurrentForm.Items.Item("1").Click(SAPbouiCOM.BoCellClickType.ct_Regular);
        }
        /// <summary>
        /// 添加右击菜单 
        /// </summary>
        /// <remarks></remarks>
        private void AddRightClickMenus()
        {
            SAPbouiCOM.Form oForm;
            oForm = CurrentForm;
            if (oForm.IsSystem) return;

            SAPbouiCOM.MenuItem oMenuItem = default(SAPbouiCOM.MenuItem);
            SAPbouiCOM.Menus oMenus = default(SAPbouiCOM.Menus);
            SAPbouiCOM.MenuCreationParams oCreationPackage = default(SAPbouiCOM.MenuCreationParams);
            string Status = string.Empty;
            try
            {
                if (CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV").GetValue("U_Status", 0).Trim() == "C")
                {
                    oCreationPackage = SBOApp.CreateObject(SAPbouiCOM.BoCreatableObjectType.cot_MenuCreationParams);
                    oCreationPackage.Type = SAPbouiCOM.BoMenuType.mt_STRING;
                    oCreationPackage.UniqueID = "Canceled";
                    oCreationPackage.String = "制作红字发票";
                    oCreationPackage.Enabled = true;

                    oMenuItem = SBOApp.Menus.Item("1280");
                    oMenus = oMenuItem.SubMenus;
                    if (!oMenus.Exists("Canceled"))
                    {
                        oMenus.AddEx(oCreationPackage);
                    }
                }
                if (CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV").GetValue("U_Status", 0).Trim() == "P")
                {
                    oCreationPackage = SBOApp.CreateObject(SAPbouiCOM.BoCreatableObjectType.cot_MenuCreationParams);
                    oCreationPackage.Type = SAPbouiCOM.BoMenuType.mt_STRING;
                    oCreationPackage.UniqueID = "Invalid";
                    oCreationPackage.String = "作废";
                    oCreationPackage.Enabled = true;

                    oMenuItem = SBOApp.Menus.Item("1280");
                    oMenus = oMenuItem.SubMenus;
                    if (!oMenus.Exists("Invalid"))
                    {
                        oMenus.AddEx(oCreationPackage);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 移除右击菜单 
        /// </summary>
        /// <remarks></remarks>
        private void RemoveRightClickMenus()
        {
            try
            {
                if (SBOApp.Menus.Exists("Canceled"))
                {
                    SBOApp.Menus.RemoveEx("Canceled");
                }
                if (SBOApp.Menus.Exists("Invalid"))
                {
                    SBOApp.Menus.RemoveEx("Invalid");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void Canceled()
        {
            SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV");
            if (dbds.GetValue("U_Status", dbds.Offset).Trim() == "C")
            {
                string DocEntry = dbds.GetValue("DocEntry", dbds.Offset).Trim();
                string SQL = "UPDATE [@AVA_OINV] SET Canceled = 'Y',U_Status = 'Q' Where DocEntry = " + DocEntry;
                SAPbobsCOM.Recordset rs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                rs.DoQuery(SQL);
                CurrentForm.Mode = SAPbouiCOM.BoFormMode.fm_FIND_MODE;
                SAPBoAddon.B1Assistant.Item.SetEnabled(CurrentForm, "3", true);
                SAPBoAddon.B1Assistant.Item.SetValue(CurrentForm, "3", DocEntry);
                CurrentForm.Items.Item("1").Click(SAPbouiCOM.BoCellClickType.ct_Regular);
            }
            else
            {
                SBOApp.MessageBox("此单据不能进行此操作");
            }
        }
        /// <summary>
        /// 作废
        /// </summary>
        private void Invalid()
        {
            SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV");
            if (dbds.GetValue("U_Status", dbds.Offset).Trim() == "P")
            {
                string DocEntry = dbds.GetValue("DocEntry", dbds.Offset).Trim();
                string SQL = "UPDATE [@AVA_OINV] SET U_Status = 'D' Where DocEntry = " + DocEntry;
                SAPbobsCOM.Recordset rs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                rs.DoQuery(SQL);
                SQL = @"UPDATE T2 
                            SET 
                                T2.U_InvoiceAmount = Case When ISNULL(T2.U_InvoiceAmount,0) - ISNULL(T0.U_Amount,0) <= 0 Then 0 Else ISNULL(T2.U_InvoiceAmount,0) - ISNULL(T0.U_Amount,0) End
                                ,T2.U_IsInvoice = 'N'
                        FROM [@AVA_OINV] T0
	                        INNER JOIN [@AVA_INV2] T1 ON T0.DocEntry = T1.DocEntry
	                        INNER JOIN ODRF T2 ON ((T1.U_Direction = 'I' And T2.ObjType = '13') Or (T1.U_Direction = 'O' And T2.ObjType = '18')) And T2.DocEntry = T1.U_BaseEntry
                        Where T0.DocEntry = {0}";
                rs.DoQuery(string.Format(SQL, DocEntry));
                CurrentForm.Mode = SAPbouiCOM.BoFormMode.fm_FIND_MODE;
                SAPBoAddon.B1Assistant.Item.SetEnabled(CurrentForm, "3", true);
                SAPBoAddon.B1Assistant.Item.SetValue(CurrentForm, "3", DocEntry);
                CurrentForm.Items.Item("1").Click(SAPbouiCOM.BoCellClickType.ct_Regular);
            }
            else
            {
                SBOApp.MessageBox("此单据不能进行此操作");
            }
        }
        /// <summary>
        /// 更新发票草稿
        /// </summary>
        private void UpdateInvoiceDraft()
        {
            SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_OINV");
            string DocEntry = dbds.GetValue("DocEntry", dbds.Offset).Trim();
            string Status = dbds.GetValue("U_Status", dbds.Offset).Trim();
            SAPbobsCOM.Recordset rs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            string SQL = string.Empty;
            if (Status == "P")
            {
                SQL = @"UPDATE T2 SET T2.U_InvoiceAmount = ISNULL(T2.U_InvoiceAmount,0) + ISNULL(T0.U_Amount,0),T2.U_IsInvoice = (Case When ISNULL(T2.U_InvoiceAmount,0) + ISNULL(T0.U_Amount,0) >= T2.DocTotal Then 'Y' Else 'N' End )
                        FROM [@AVA_OINV] T0
	                        INNER JOIN [@AVA_INV2] T1 ON T0.DocEntry = T1.DocEntry
	                        INNER JOIN ODRF T2 ON ((T1.U_Direction = 'I' And T2.ObjType = '13') Or (T1.U_Direction = 'O' And T2.ObjType = '18')) And T2.DocEntry = T1.U_BaseEntry
                        Where T0.DocEntry = {0}";
                rs.DoQuery(string.Format(SQL, DocEntry));
            }
        }
        #endregion
    }
}
